package org.bigjava.novelplatform.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileReader;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.bigjava.novelplatform.common.exception.UserActionException;
import org.bigjava.novelplatform.common.utils.R;
import org.bigjava.novelplatform.entity.Books;
import org.bigjava.novelplatform.mapper.BooksMapper;
import org.bigjava.novelplatform.service.CommonService;
import org.bigjava.novelplatform.service.RabbitmqService;
import org.bigjava.novelplatform.service.WriterService;
import org.bigjava.novelplatform.service.impl.AuthorBookServiceImpl;
import org.bigjava.novelplatform.service.impl.AuthorChapterServiceImpl;
import org.bigjava.novelplatform.service.impl.UserServiceImpl;
import org.bigjava.novelplatform.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static org.bigjava.novelplatform.common.constant.NovelInfoConstant.*;
import static org.bigjava.novelplatform.common.exception.ExceptionCodeMessage.NON_COMPLIANT_PARAMETERS;
import static org.bigjava.novelplatform.common.exception.ExceptionCodeMessage.UNRECOGNIZED_TYPE;

/**
 * @author ykh
 * @create 2022-05-10 22:09
 */
@Slf4j
@RestController
@RequestMapping("/api/writer")
public class WriterController {
    @Resource
    private AuthorBookServiceImpl authorBookService;

    @Resource
    private RabbitmqService rabbitmqService;

    @Resource
    private WriterService writerService;

    @Resource
    private AuthorChapterServiceImpl authorChapterService;

    @Resource
    private CommonService commonService;

    @GetMapping("/selectBook/{id}")
    public R selectBook(@PathVariable("id") Integer bookId,UserInfoVo userInfoVo){
        WriterBookVo writerBookVo = writerService.selectBook(bookId,userInfoVo.getId());
        return R.ok().setData(writerBookVo);
    }


    /**
     * 添加一本书
     * @param bookCreateVo
     * @param userInfoVo
     * @return
     */
    @PostMapping("/addBook/{bookId}")
    public R addBook(@RequestPart(value = "file",required = false) MultipartFile multipartFile,
                     @Validated BookCreateVo bookCreateVo,
                     @PathVariable("bookId") Integer bookId,
                     UserInfoVo userInfoVo) throws IOException {
        Books books = new Books();
        String url = BOOK_COVER_URL_PATH;
        if (multipartFile != null) {
            String path = BOOK_COVER_DISK_PATH;
            String filename = multipartFile.getOriginalFilename();
            path += filename;
            url += filename;
            File file = new File(path);
            multipartFile.transferTo(file);
            books.setBookImgUrl(url);
        }
        BeanUtils.copyProperties(bookCreateVo,books);
        if(bookId.equals(0)){
            authorBookService.publishBooks(books,userInfoVo.getId());
        }else{
            books.setId(bookId);
            writerService.updateBook(books,userInfoVo.getId());
        }
        return R.ok();
    }

    /**
     * 上架书籍
     * @param bookId
     * @return
     */
    @GetMapping("/sale/{bookId}")
    public R sale(@PathVariable("bookId")Integer bookId,UserInfoVo userInfoVo){
        writerService.sale(bookId,userInfoVo.getId());
        return R.ok();
    }

    /**
     * 完结书籍
     * @param bookId
     * @param userInfoVo
     * @return
     */
    @GetMapping("/theBookIsOver/{bookId}")
    public R theBookIsOver(@PathVariable("bookId")Integer bookId,UserInfoVo userInfoVo){
        writerService.theBookIsOver(bookId,userInfoVo.getId());
        return R.ok();
    }


    /**
     * 查询连载书籍
     * @param userInfoVo
     * @return
     */
    @GetMapping("/inSerial")
    public R inSerial(UserInfoVo userInfoVo){
        Books book = writerService.selectInSerial(userInfoVo.getId());
        return R.ok().setData(book);
    }


    /**
     * 获取作品信息
     * @param userInfoVo
     * @return
     */
    @GetMapping("/worksAll")
    public R worksAll(UserInfoVo userInfoVo){
        //获取所有作品
        List<Books> simpleBookVoList = writerService.getWorksByUserId(userInfoVo.getId());
        return R.ok().setData(simpleBookVoList);
    }


    /**
     * 获取作者信息
     * @param userInfoVo
     * @return
     */
    @GetMapping("/writerInfo")
    public  R getWriterInfo(UserInfoVo userInfoVo){
        WriterInfoVo writer = writerService.getWriterInfo(userInfoVo.getId());
        return R.ok().setData(writer);
    }

    /**
     * 保存
     * @param chapterContent
     * @param userInfoVo
     * @return
     */
    @PostMapping("/saveChapter")
    public R saveChapter(@RequestBody ChapterContent chapterContent, UserInfoVo userInfoVo){
        ChapterContent content = writerService.saveChapter(chapterContent, userInfoVo.getId());
        return R.ok().setData(content);
    }

    /**
     * 删除章节
     *
     * @return
     */
    @PostMapping("/deleteChapter")
    public R deleteChapter(@RequestBody Map<String,Long> map, UserInfoVo userInfoVo){
        writerService.deleteChapter(map.get("chapterId"),userInfoVo.getId());
        return R.ok();
    }

    @PostMapping("/deleteChapter/{bookId}")
    public R deleteList(@PathVariable("bookId") Integer bookId, UserInfoVo userInfoVo){
        List<ChapterContent> list =  writerService.selectDeleteList(bookId,userInfoVo.getId());
        return R.ok().setData(list);
    }

    /**
     * 还原章节
     * @param map
     * @param userInfoVo
     * @return
     */
    @PostMapping("/restoreChapter")
    public R restoreChapter(@RequestBody Map<String,Long> map, UserInfoVo userInfoVo){
        writerService.restoreChapter(map.get("chapterId"),userInfoVo.getId());
        return R.ok();
    }

    /**
     * 草稿列表
     * @param bookId
     * @param userInfoVo
     * @return
     */
    @GetMapping("/selectDraftList")
    public R selectDraftList(Integer bookId,UserInfoVo userInfoVo){
        List<ChapterContent> chapterContentList = writerService.SelectDraftList(bookId,userInfoVo.getId());
        return R.ok().setData(chapterContentList);
    }

    /**
     * 发布列表
     * @return
     */
    @GetMapping("/selectPublishList")
    public R selectPublishList(Integer bookId,UserInfoVo userInfoVo){
        List<ChapterContent> chapterContentList = writerService.selectPublishList(bookId, userInfoVo.getId(), 10);
        return R.ok().setData(chapterContentList);
    }



    /**
     * 章节内容
     * @param bookId
     * @param chapterId
     * @return
     */
    @GetMapping("/chapter")
    public R selectChapter(Integer bookId, Long chapterId){
        String chapter = writerService.selectChapter(bookId, chapterId);
        return R.ok().setData(chapter);
    }

    /**
     * 保存为存稿
     * @return
     */
    @PostMapping("/saveAsDraft")
    public R saveAsDraft(@RequestBody ChapterContent chapterContent, UserInfoVo userInfoVo){
        ChapterContent content = writerService.saveAsDraft(chapterContent, userInfoVo.getId());
        return R.ok().setData(content);
    }

    /**
     * 获取指定id章节的历史版本
     */
    @GetMapping("/getChapterHistory")
    public R getChapterHistory(String chapterId) {
        List<String> list;
        try {
            list = authorChapterService.getChapterHistory(Long.valueOf(chapterId));
        } catch (Exception e) {
            throw new UserActionException(NON_COMPLIANT_PARAMETERS);
        }
        return R.ok().setData(list);
    }

    /**
     * 获取符合文件名的章节内容
     */
    @GetMapping("/getChapterContent")
    public R getChapterContent(String fileName) {
        String[] list = fileName.split("_");
        String bookUrl = authorChapterService.getChapterUrlById(Long.valueOf(list[1]));
        String chapterUrl = bookUrl + "\\DeletedChapter\\" + fileName + ".txt";
        File file = FileUtil.file(chapterUrl);
        if (!file.exists()) {
            return R.error(NON_COMPLIANT_PARAMETERS);
        }
        FileReader fileReader = new FileReader(file);
        return R.ok().setData(StrUtil.builder(fileReader.readString()));
    }

    /**获取回收站内的的内容*/
    @GetMapping("/getChapterDeleted")
    public List<String> getChapterDeleted(String bookId) {
        System.out.println(bookId);
        return authorChapterService.getChapterDeleted(Integer.valueOf(bookId));
    }

    /**
     * 发布
     * @param releaseVo
     * @param userInfoVo
     * @return
     */
    @PostMapping("/release")
    public R release (@RequestBody ReleaseVo releaseVo,
                      UserInfoVo userInfoVo){
        releaseVo.setUserId(userInfoVo.getId());
        switch (releaseVo.getReleaseType()){
            case "1":
                writerService.release(releaseVo);
                break;
            case "2":
                rabbitmqService.timedTask(releaseVo);
                break;
            default:
                throw new UserActionException(UNRECOGNIZED_TYPE);
        }
        return R.ok();
    }
}
